
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: localStorage.getItem('user')? localStorage.getItem('user') : null,
    //若localStorage存在token，将值赋给Vuex.state.token
    token: localStorage.getItem('token') ? localStorage.getItem('token') : null
  },
  mutations: {
    setUser(state, user){
      console.log(JSON.stringify(user));
      state.user = user;
      localStorage.setItem("user",JSON.stringify(user));
      console.log(localStorage.getItem('user'));
    },

    //登录后通过setToken存入token token保存在state和localStorage中
    setToken(state, token) {
      state.token = token;
      localStorage.setItem("token", token);     //存储token
    },
    //登出后通过delToken清除token
    delToken(state) {
      state.token = '';
      localStorage.removeItem("token");    //删除token
    }
  }
})
